<?php

namespace app\common\core;

class FileHand
{
    protected static $init;
    protected $config;
    public static function init(array $config=[])
    {
        if(is_null(self::$init)){
            self::$init = new static($config);
        }
        return self::$init;
    }
    /**
     * 获取目录下所有文件
     * @param string $dir 路径
     * @param string $type 文件类型[all/dir/file]
     * @param array  $excluded 排除的文件或文件夹
     * @param array  $only 只有文件夹或文件
     * @param boolean $has_child 是否递归
     * @param boolean $is_path 是否路径
     * @return void
     */
    public function get_dir_path(string $dir,string $type="all",array $excluded=[],array $only = [],bool $has_child=false,bool $is_path=false)
    {
        if(!is_dir($dir)&&!is_file($dir)){
            return [];
        }
        $dir = str_replace('\\', '/', $dir);
        $dir = rtrim($dir,'/').'/';
        $dirsList = scandir($dir);
        $dirsList = array_filter($dirsList,function($item){
            return $item!='.'&&$item!='..';
        });
        $all = [];
        $filter = function ($dir,$item)use($type,$excluded,$only,$is_path){
            $path = $dir.$item;
            if(!empty($excluded)){
                if(in_array($item,$excluded)){
                    return [];
                }
            }
            if(!empty($only)){
                if(!in_array($item,$only)){
                    return [];
                }
            }
            if($type!='all'){
                if($type=='dir'&&!is_dir($path)){
                    return [];
                }
                if($type=='file'&&is_dir($path)){
                    return [];
                }
            }
            if($is_path){
                return $path;
            }else{
                return $item;
            }
        };
        foreach ($dirsList as $key => $value){
            if($has_child){
                if(is_dir($dir.$value)){
                    $tem = $filter($dir,$value);
                    if(!empty($tem)){
                        $all[] = $tem;
                    }
                    $all = array_merge($all,$this->get_dir_path(dir:$dir.$value,type:$type,excluded: $excluded,only: $only,has_child: $has_child,is_path: $is_path));
                }else{
                    $tem = $filter($dir,$value);
                    if(!empty($tem)){
                        $all[] = $tem;
                    }
                }
            }else{
                $tem = $filter($dir,$value);
                if(!empty($tem)){
                    $all[] = $tem;
                }
            }
        }
        $all = array_unique($all);
        return $all;

    }
}